package service;

import controller.SocketServerController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.LoggerUtil;
import utils.Role;

import java.util.List;

public class NodeService {
    private Node selfNode;
    private List<Node> clusterNodes;
    private ClusterSyncService clusterSyncService;
    private final Logger LOGGER = LoggerFactory.getLogger(NodeService.class);


    public NodeService(Node selfNode, List<Node> clusterNodes) {
        this.selfNode = selfNode;
        this.clusterNodes = clusterNodes;

    }

    public void setClusterSyncService(ClusterSyncService clusterSyncService) {
        this.clusterSyncService = clusterSyncService;
    }

    public void start() {
        if (selfNode.getRole() == Role.MASTER) {
            // 启动读写服务
            startMasterService();
        } else {
            // 启动只读服务，定期同步数据
            startReplicaService();
        }
    }

    private void startMasterService() {
        LoggerUtil.info(LOGGER, "Starting as MASTER node");
        clusterSyncService.start();
    }

    private void startReplicaService() {
        LoggerUtil.info(LOGGER, "Starting as SLAVE node");
        clusterSyncService.start();

        // 从节点启动时从主节点同步全量数据
        syncInitialData();
    }

    private void syncInitialData() {
        // 实现从主节点同步初始数据的逻辑
        // 可以是快照复制或WAL重放
    }
}

